package com.hnepri.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
    /**
     * 写日志或者普通文件
     * @param path
     * @param msg
     */
    public static void writeFile(String path, String msg) {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), "utf-8"));
            pw.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (pw != null) pw.close();
        }
    }

    /**
     * 写日志
     * @param path
     * @param msg
     * @param isAppend 是否启用追加模式
     */
    public static void writeFile(String path, String msg, boolean isAppend) {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path, isAppend), "utf-8"));
            pw.println(msg);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (pw != null) pw.close();
        }
    }
    /**
     * 读取一个文件中的所有行组成list
     * @param path  文件路径
     * @param charset 字符编码
     * @return
     */
    public static List<String> getLineList(String path, String charset) {
        List<String> lines = new ArrayList<>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(path), charset));
            String msg = null;
            while((msg = br.readLine()) != null) {
                if (msg.trim().equals(""))continue;
                lines.add(msg);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return lines;
    }

    /**
     * 把字符串列表写入文件
     * @param lines
     */
    public static void writeLines(List<String> lines, String path, String charset) {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), charset)));
            for (String line: lines) {
                pw.println(line);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }
}
